<template>
  <Card :bordered="false">
    <p slot="title">
      <Icon type="md-trophy"></Icon>
      容器组管理
    </p>
    <div style="padding-bottom: 10px;">
      <!-- <Row :gutter="16">
        <Col span="6">
          <Select v-model="namespace"  placeholder="请选择命名空间" @on-change="PodsData">
            <Option v-for="item in namespaced" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="6" offset="12">
          <Input search placeholder="Search ..." v-model="search_value" @on-search=searchPods />
        </Col>
      </Row> -->
      <Row :gutter="24">
        <Col span="4">
          <Select v-model="cloud_name"  placeholder="请选择云平台" @on-change="GetCloudNamespaces">
            <Option v-for="item in cloud_list" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="4">
          <Select v-model="namespace"  placeholder="请选择命名空间" clearable @on-change="PodsData" ref="pods_list">
            <Option v-for="item in namespaced" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="4" offset="12">
          <Input search placeholder="Search ..." v-model="search_value" @on-search=searchPods />
        </Col>
      </Row>
    </div>
    <Table border :loading="loading" :columns="columns" :data="data">
      <template slot-scope="{ row, index }" slot="index">
        <span>{{index+1}}</span>
      </template>
      <template slot-scope="{ row, index }" slot="status">
        <span v-if="`${row.status}`=='Pending'" style="color:#ed4014">运行异常</span>
        <span v-else style="color:#19be6b">正在运行</span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <Button v-if="permission.pods_restart === '1'" type="warning" size="small" @click="restart(index)">重启</Button>
        <span style="color:#ed4014" v-else>无权限</span>
      </template>
    </Table>
    <div style="padding-top: 10px;" v-if="count">
      <template>
        <Page :total="count" show-total :page-size-opts="[10,25,40,55,70,100]" current.sync="current" show-elevator show-sizer @on-change="switchPage" @on-page-size-change="switchPageSize" />
      </template>
    </div>
  </Card>
</template>

<script>
import { namespaceList, podsList, podsAllSearch } from '@/api/production'

  export default {
    data () {
      return {
        loading: false,
        count: '',
        page: 1,
        pageSize: 10,
        search_value: '',
        namespace: '',
        namespaced: [],
        cloud_name: '',
        cloud_list: [
          {value: 'aliyun', label: '阿里云集群'},
          // {value: 'aws-stg', label: 'AWS-STG'},
          // {value: 'aws-prod', label: 'AWS-PROD'}
        ],
        columns: [
          {
            title: '序号',
            slot: 'index',
            width: '100',
            align: 'center'
          },
          {
            title: '容器名称',
            key: 'name'
          },
          {
            title: '项目名称',
            key: 'deployment_name'
          },
          {
            title: '运行状态',
            key: 'status',
            slot: 'status'
          },
          {
            title: '重启次数',
            key: 'restart_number'
          },
          {
            title: '容器IP',
            key: 'pod_ip'
          },
          {
            title: '节点IP',
            key: 'node_ip'
          },
          {
            title: '启动时间',
            key: 'start_time'
          },
          {
            title: '创建日期',
            key: 'create_time'
          },
          {
            title: '操作',
            slot: 'action',
            width: 120,
            align: 'center'
          }
        ],
        data: [],
        permission: ''
      }
    },
    methods: {
      // 获取用户操作权限
      get_permission () {
        const auth = JSON.parse(sessionStorage.getItem('permission'))
        this.permission = auth.child
      },
      GetCloudNamespaces () {
        this.$refs.pods_list.clearSingleSelect();
        this.namespaced = [];
        this.data = [];
        this.count = 0;
        this.namespace_list({'cloud_name': this.cloud_name})
      },
      // 获取缓存数据
      namespace_list (cloud) {
        namespaceList(cloud).then(res => {
          var namespace_res = res.data.results
          for (const namespace in namespace_res) {
            if (namespace_res[namespace]['name']==='prod' || namespace_res[namespace]['name']==='uat') {
              var auth = this.permission[`production_${namespace_res[namespace]['name']}_view`]
              if (auth==='1') {
                var select_men = {
                  'value': namespace_res[namespace]['name'],
                  'label': namespace_res[namespace]['name']
                }
                this.namespaced.push(select_men)
              }
            } else {
              var select_men = {
                'value': namespace_res[namespace]['name'],
                'label': namespace_res[namespace]['name']
              }
              this.namespaced.push(select_men)
            }
          }
        })
      },
      //获取pod数据
      PodsData (CronStatus) {
        if (this.cloud_name.length !== 0 && this.namespace !== undefined) {
          if (CronStatus === true) {
            this.loading = false;
          } else {
            this.loading = true;
          }
          if (this.search_value.length!==0&&this.count<10){
            this.page = 1;
            this.pageSize = 10;
          }
          var params = {
            'cloud_name': this.cloud_name,
            'namespace_name':this.namespace,
            'Page': this.page,
            'PageSize': this.pageSize,
            'searchName': this.search_value
          }
          if (this.namespace.length !=0 ) {
            podsList(params).then(res => {
              this.loading = false;
              this.count = res.data.count;
              this.data = res.data.results;
            }).catch(err => {
              this.$Message.error("列表获取失败!")
            })
          }
        }
      },
      // 获取页码并发起请求
      switchPage (page) {
        this.page = page
        this.PodsData()
      },
      // 获取选择切换的每页条数并发起请求
      switchPageSize (pageSize) {
        this.page = 1
        this.pageSize = pageSize
        this.PodsData()
      },
      // 搜索
      searchPods () {
        if (this.namespace.length !=0 ) {
          this.loading = true;
          podsAllSearch(this.cloud_name, this.namespace, this.search_value).then(res => {
            this.loading = false;
            this.count = res.data.count
            this.data = res.data.results
          }).catch(err => {
            this.$Message.error('接口请求失败!')
          })
        } else {
          this.$Message.error("请选择应用环境!")
        }
      },
      // 重启pod
      restart (index) {
        var pod_name = this.data[index].name
        var params = {'namespace_name':this.namespace,'pod_name':pod_name}
        podsList(params).then(res => {
          this.$Message.success(`${pod_name}重启成功!`)
          this.PodsData()  //刷新数据
        }).catch(err => {
          this.$Message.error(`${pod_name}重启失败!`)
        })
      },
      // 定时获取数据并重新加载页面
      cronGetPods () {
        this.cronGet = setInterval(() => this.PodsData(true), 10000)
      }
    },
    created () {
      this.get_permission();
      // this.namespace_list();
      this.cronGetPods();
    },
    beforeDestroy () {
      // 退出当前页面时清除此定时请求任务
      clearInterval(this.cronGet)
    }
  }
</script>